package com.zplh.zplh_android_yk.ui;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.zplh.zplh_android_yk.BuildConfig;
import com.zplh.zplh_android_yk.R;
import com.zplh.zplh_android_yk.TaskManager;
import com.zplh.zplh_android_yk.UserManager;
import com.zplh.zplh_android_yk.bean.TaskBean;
import com.zplh.zplh_android_yk.event.JpushEvent;
import com.zplh.zplh_android_yk.services.TaskSender;
import com.zplh.zplh_android_yk.utils.RxBus;

import java.util.Vector;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import zplh.com.commonlibrary.utils.LogUtils;
import zplh.com.commonlibrary.utils.ToastUtils;

public class MainActivity extends BaseActivity implements TaskManager.TaskListener, SwipeRefreshLayout.OnRefreshListener {
    private static boolean isExit=false;

    @BindView(R.id.fl_content)
    FrameLayout flContent;
    @BindView(R.id.fl_left_content)
    FrameLayout flLeftContent;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.drawer)
    DrawerLayout drawer;
    @BindView(R.id.jpush_name)
    TextView mJpushName;
    @BindView(R.id.tv_state)
    TextView tvState;
    String currentAlias = "";
    private LeftFragment leftFragment;
    private MainFragment mainFragment;
    private ActionBarDrawerToggle toggle;

    @Override
    int getLayoutId() {
         return R.layout.activity_main;
    }

    @Override
    void onFirstStart() {
        initView();
        initFragment();

        toolbar.setSubtitle(BuildConfig.VERSION_NAME);
        TaskManager.init(new TaskManager.InitListener() {
            @Override
            public void initSuccess(TaskManager taskManager) {
                Vector<TaskBean> taskBeans = taskManager.getTaskArrays();
                mainFragment.upDataTask(taskBeans);
                initRxBus();
                initServices();
                initPush();
            }

            @Override
            public void initError(String error) {
                ToastUtils.showToastError(MainActivity.this, error);
            }
        });
        TaskManager.getInstance().setTaskListener(this);

    }

    @SuppressLint("CheckResult")
    private void initRxBus() {
        RxBus.getInstance().toObservable().map(o -> ((JpushEvent) o))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(event -> {
                    if (event!=null){
                        if (event.getType() == 0) {
                            currentAlias = event.getAlias();
                            mJpushName.setText(currentAlias);
                        }else {

                            if (event.getSatate().equals("断开"))
                                tvState.setTextColor(getResources().getColor(R.color.red_btn_bg_color));
                            else
                                tvState.setTextColor(Color.WHITE);

                            tvState.setText("网络状态:"+event.getSatate());
                        }
                    }
                });
    }

    @OnClick(R.id.tv_state)
    public void onJpushClick(View view){
                    JPushInterface.resumePush(this);

    }


    @SuppressLint("CheckResult")
    private void initPush() {
        Observable.timer(10,TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> {
                    JPushInterface.setAlias(MainActivity.this,10086,UserManager.getInstance().getMid());
                    CloudPushService pushService = PushServiceFactory.getCloudPushService();

                    pushService.bindAccount(UserManager.getInstance().getMid(), new CommonCallback() {
                        @Override
                        public void onSuccess(String s) {
                            ToastUtils.showToastSuccess(MainActivity.this,"阿里推送绑定成功");
                        }

                        @Override
                        public void onFailed(String s, String s1) {
                            LogUtils.d("阿里推送",s);
                        }
                    });
                });

    }

    private void initServices() {
        Intent intent = new Intent(this, TaskSender.class);
        startService(intent);
    }




    private boolean isPressedBackOnce = false;
    private long firstPressedTime = 0;
    private long secondPressedTime = 0;
    @Override
    public void onBackPressed() {
        if (isPressedBackOnce) {
            // 说明已经按了一次 这是第二次
            secondPressedTime = System.currentTimeMillis();
            if (secondPressedTime - firstPressedTime > 3000) {
                // 第一次点击作废了，重新计算
                ToastUtils.showToastSuccess(MainActivity.this,"再点一次退出");
                isPressedBackOnce = true;
                firstPressedTime = System.currentTimeMillis();
            } else {
                // 说明两秒之内点击的第二次
                finish();
                System.exit(0);
                // 状态回复至初
                isPressedBackOnce = false;
                firstPressedTime = 0;
                secondPressedTime = 0;
            }
        } else {
            // 说明第一次
            ToastUtils.showToastSuccess(MainActivity.this,"再点一次退出");
            isPressedBackOnce = true;
            firstPressedTime = System.currentTimeMillis();
        }
    }


    @Override
    protected void onDestroy() {
        Intent intent = new Intent(this, TaskSender.class);
        stopService(intent);
        super.onDestroy();

    }


    private void initFragment() {
        leftFragment = LeftFragment.newInstance();
        mainFragment = MainFragment.newInstance();
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.fl_left_content, leftFragment)
                .add(R.id.fl_content, mainFragment)
                .commitAllowingStateLoss();

    }


    private void initView() {

        setSupportActionBar(toolbar);
        /*显示Home图标*/
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toggle = new ActionBarDrawerToggle(this, drawer, toolbar, 0, 0);
        drawer.addDrawerListener(toggle);
        /*同步drawerlayout的状态*/
        toggle.syncState();

    }


    public static void starter(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
        ((Activity) context).finish();
    }

    //新增任务 刷新界面
    @Override
    public void onAddTask(TaskBean taskBean) {

        mainFragment.upDataTask(TaskManager.getInstance().getTaskArrays());
    }


    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        mainFragment.refresh();
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

    }

    @Override
    public void onDeleteTask(TaskBean taskBean) {

    }

    @Override
    public void onTaskRefresh(TaskBean taskBean) {
        this.runOnUiThread(() -> mainFragment.refresh());
    }

    @Override
    public void onRefresh() {
        mainFragment.refresh();
    }
}
